<template>
  <el-dialog
    :model-value="showPayDialog"
    title="请使用微信扫码支付"
    width="300"
    @close="resetForm"
    :close-on-click-modal="false"
  >
    <div class="content">
      <qrcode-vue :value="qrValue" :size="200" />
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
  import QrcodeVue from 'qrcode.vue'
  import { ref, onMounted, onUnmounted } from 'vue'
  import { getQrCode, getPaymentStatus } from '@/api/ApiList'
  import { ElMessage, ElMessageBox } from 'element-plus'

  const props = defineProps({
    showPayDialog: {
      type: Boolean,
      default: false
    },
    ordersNo: {
      type: String
    }
  })

  const emit = defineEmits(['closeModal'])

  let timer: any = null
  const qrValue = ref()

  async function getQrCodeData() {
    const res = await getQrCode({
      ordersNo: props.ordersNo
    })
    if (res.code === '00000') {
      qrValue.value = res.data.codeUrl
      startPolling()
    } else {
      ElMessageBox.confirm(res.msg, 'Warning', {
        showCancelButton: false,
        type: 'warning'
      }).then(() => {})
    }
  }

  function stopPolling() {
    if (timer) {
      clearInterval(timer)
      timer = null
    }
  }

  function startPolling() {
    stopPolling()
    timer = setInterval(() => {
      getPayStatus()
    }, 3000)
  }

  async function getPayStatus() {
    try {
      const res = await getPaymentStatus({
        ordersNo: props.ordersNo
      })
      if (res.code === '00000') {
        const status = res.data.status
        if (status === 1) {
          ElMessage.success('支付成功')
          emit('closeModal')
          stopPolling()
        }
      } else {
      }
    } catch {
    } finally {
    }
  }

  function resetForm() {
    emit('closeModal')
  }

  onMounted(() => {
    getQrCodeData()
  })

  onUnmounted(() => {
    stopPolling()
  })
</script>

<style scoped lang="scss">
  .content {
    display: flex;
    justify-content: center;
  }
</style>
